<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <!-- 搜索与添加 -->
        <el-col :span="8">
          <el-input placeholder="用户名称" v-model="queryInfo.keyWord" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="电话" prop="phone"></el-table-column>
        <el-table-column label="登录状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.lstatus" disabled></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" sortable>
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="用户详情"
              placement="top"
              :enterable="false"
            >
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="openDatil(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageIndex"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 用户详情 -->
        <el-dialog title="用户详情" :visible.sync="dialogVisible" width="30%">
          <span>用户名{{userDatil.name}}</span>
          <el-divider></el-divider>
          <span>手机号：{{userDatil.phone}}</span>
          <el-divider></el-divider>
          <span>邮箱：{{userDatil.email}}</span>
          <el-divider></el-divider>
          <span>年龄：{{userDatil.age}}</span>
          <el-divider></el-divider>
          <span>出生年月：{{userDatil.birthday}}</span>
          <el-divider></el-divider>
          <span>性别：{{userDatil.sex}}</span>
          <el-divider></el-divider>
          <span>家庭住址：{{userDatil.address}}</span>
          <el-divider></el-divider>
          <span>爱好：{{userDatil.like}}</span>
          <el-divider></el-divider>
          <span>个性签名：{{userDatil.signature}}</span>
          <el-divider></el-divider>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
          </span>
        </el-dialog>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="密 码" prop="pwd">
          <el-input type="password" v-model="addForm.pwd"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="权限">
          <el-input v-model="addForm.rootId"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="出生年月">
          <el-date-picker v-model="addForm.birthday" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addForm.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="家庭地址">
          <el-input v-model="addForm.address"></el-input>
        </el-form-item>
        <el-form-item label="爱好">
          <el-input v-model="addForm.like"></el-input>
        </el-form-item>
        <el-form-item label="个性签名">
          <el-input v-model="addForm.signature"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="30%" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="密 码" prop="pwd">
          <el-input type="password" v-model="editForm.pwd"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="rootId">
          <el-input v-model="editForm.rootId"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="出生年月">
          <el-date-picker v-model="editForm.birthday" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="家庭地址">
          <el-input v-model="editForm.address"></el-input>
        </el-form-item>
        <el-form-item label="爱好">
          <el-input v-model="editForm.like"></el-input>
        </el-form-item>
        <el-form-item label="个性签名">
          <el-input v-model="editForm.signature"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    //验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      //验证手机号是否存在
      this.userlist.forEach(e => {
        if (e.phone === value) {
          cb(new Error("手机号已存在"));
        }
      });
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };

    //验证手机号的规则
    var checkMobileOfEdit = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 参数对象
      queryInfo: {
        keyWord: "",
        pageIndex: 1,
        pageSize: 2
      },
      userlist: [],
      editForm: {},
      userDatil:{},
      total: 0,
      //控制用户对话的显示与隐藏
      addDialogVisible: false,
      //控制修改用户对话的显示与隐藏
      editDialogVisible: false,
      dialogVisible: false,
      //添加表单数据
      addForm: {
        name: "",
        pwd: "",
        phone: "",
        rootId: "",
        like: "",
        sex: "",
        address: "",
        email: "",
        signature: "",
        birthday: "",
      },
      //添加表单验证规则
      addFormRules: {
        name: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度在2到10个字符之间", trigger: "blur" }
        ],
        pwd: [
          { required: true, message: "请输入密码名称", trigger: "blur" },
          { min: 6, max: 15, message: "长度在6到15个字符之间", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      //修改表单验证规则
      editFormRules: {
        pwd: [
          { required: true, message: "请输入密码名称", trigger: "blur" },
          { min: 6, max: 15, message: "长度在6到15个字符之间", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: checkMobileOfEdit, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const res = await this.$http.post(
        "user/getUserByCondition",
        this.queryInfo
      );
      if (res.status !== 200) {
        return this.$message.error("获取用户列表失败!");
      }
      res.data.data.forEach(element => {
        element.lstatus = element.lstatus == 0 ? false : true;
      });
      console.log(res.data.data);
      this.userlist = res.data.data;
      this.total = res.data.total;
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pageIndex = newPage;
      this.getUserList();
    },
    //监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        await this.$http
          .post("user/save", this.addForm)
          .then(resp => {
            if (resp.status !== 201) return this.$message.error("添加失败");
            this.$message.success("添加成功");
            this.addDialogVisible = false;
            this.getUserList();
          })
          .catch(() => {
            this.$message.error("异常！");
          });
      });
    },
    async openDatil(id){
      const res = await this.$http.get(
        "user/getUserInfoById/"+id);
      if (res.status !== 200) {
        return this.$message.error("获取用户列表失败!");
      }
      this.userDatil = res.data;
      this.dialogVisible = true
    },
    //展示修改对话框
    showEditDialog(row) {
      this.editForm = row;
      this.editDialogVisible = true;
    },
    //修改信息
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        this.editForm.lstatus = this.editForm.lstatus == false ? "0" : "1";
        await this.$http
          .post("user/update", this.editForm)
          .then(resp => {
            if (resp.status !== 201) return this.$message.error("更新失败");
            this.$message.success("更新成功");
            this.editDialogVisible = false;
            this.getUserList();
          })
          .catch(() => {
            this.$message.error("异常！");
          });
      });
    },
    //删除用户
    async removeUserById(id) {
      const cont = await this.$confirm("是否删除该用户信息", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);

      if (cont !== "confirm") {
        return this.$message.info("已取消删除");
      }

      await this.$http
        .delete("user/delete/" + id)
        .then(resp => {
          if (resp.data !== 1) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getUserList();
        })
        .catch(() => {
          this.$message.error("异常！");
        });
    }
  }
};
</script>

<style lang="less" scoped>
</style>